import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar进度条
import 'nprogress/nprogress.css' // progress bar style进度条样式
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist白名单
// 前置守卫
router.beforeEach(async(to, from, next) => {
  // start progress bar开启进度条
  NProgress.start()

  //   // set page title
  //   document.title = getPageTitle(to.meta.title)

  //   // determine whether the user has logged in
  //   const hasToken = getToken()

  if (store.getters.token) {
    if (to.path === '/login') {
      //       // if is logged in, redirect to the home page
      next('/')
      //       NProgress.done()
    } else {
      //       const hasGetUserInfo = store.getters.name
      //       if (hasGetUserInfo) {
      if (!store.getters.userId) {
        // 获取用户资料
        const { roles } = await store.dispatch('user/getUserInfo')
        // 获取路由
        const routes = await store.dispatch('permission/filterRoutes', roles.menus)
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])// 添加动态路由到路由表 404放在动态路由的最后
        next(to.path) // addRoutes之后的固定写法 跳转到相应地址
      }
      next()
    }
  } else {
  //         try {
  //           // get user info
  //           await store.dispatch('user/getInfo')

    //           next()
    //         } catch (error) {
    //           // remove token and go to login page to re-login
    //           await store.dispatch('user/resetToken')
    //           Message.error(error || 'Has Error')
    //           next(`/login?redirect=${to.path}`)
    //           NProgress.done()
    //         }
    //       }
    //     }
    //   } else {
    //     /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      //       // in the free login whitelist, go directly
      next()
    } else {
      //       // other pages that do not have permission to access are redirected to the login page.
      next('/login')
      //       NProgress.done()
    }
  }
  // finish progress bar关闭进度条
  NProgress.done()
})
// 后置守卫
router.afterEach(() => {
  // finish progress bar关闭进度条
  NProgress.done()
})
